<?php
namespace app\admin\controller;

use app\common\model\DistributeUser;
use app\common\model\OrderOperate;
use app\common\model\OrderProduct;
use think\Db;
use think\Loader;
use think\Request;
use app\common\model\Product as ProductModel;
use app\common\model\Company as CompanyModel;
use app\admin\tool\Parser;
use app\common\model\Enroll as EnrollModel;
use app\common\model\Order as OrderModel;
use app\common\model\OrderProduct as OrderProductModel;
use app\common\model\OrderOperate as OrderOperateModel;
use app\common\model\Exhibition as ExhibitionModel;

/**
 * 客服对订单的控制
 * Class OrderService
 * @package app\admin\controller
 */
class OrderService extends Base{

    /**
     * 目前只对用户筛选
     * @param Request $request
     * @return \think\response\View
     * @throws
     */
    public function index(Request $request){
        $user_id = $request->param('user_id');
        if(!$user_id){
            $this->error("请选择一个用户");
        }
        $distribute_user  = DistributeUser::where(['admin_id'=>$this->admin->id,'user_id'=>$user_id])->find();
        if(!$distribute_user){
            $this->error("该用户不存在 或者权限限制");
        }

        $exhibition = ExhibitionModel::where('exhibition_time','>',time())->where('state',0)->order('exhibition_time desc')->find();
        $model = OrderModel::where('user_id',$user_id)->where('exhibition_id',$exhibition['id'])->where('state','<>','-1')->order('add_time desc')->paginate(10);

        $this->data['title'] = '订单列表';
        $this->data['model'] = $model;
        $this->data['parser'] = new Parser();
        $this->data['column'] = $this->column();

        return view('',$this->data);
    }


    /**
     * @param Request $request
     * @return \think\response\View
     * @throws
     */
    public function add(Request $request){
        $user_id = $request->param('user_id');
        if(!$user_id){
            $this->error("请先选择用户");
        }
        //判断用户是否存在 是否属于该客服
        $distribute_user  = DistributeUser::where(['admin_id'=>$this->admin->id,'user_id'=>$user_id])->find();
        if(!$distribute_user){
            $this->error("该用户不存在 或者权限限制");
        }

        $this->data['title'] = '添加订单';
        $this->data['user_id'] =  $user_id;
        $this->data['expo'] = CompanyModel::where(['type'=>3])->select(); //展览中心不会很多

        return view("",$this->data);
    }


    /**
     * 客服修改订单状态 只有被财务审核不通过的订单才可以修改
     * @param Request $request
     * @throws
     * @return \think\response\View
     */
    public function edit( Request  $request ){
        $id = $request->param('id');
        $order = OrderModel::get($id);
        if(!$order){
            $this->error("非法操作");
        }

        //判断是否属于当前客服的订单  根据user_id 判断

        $priv = DistributeUser::where(['admin_id'=>$this->admin->id,'user_id'=>$order->user_id,'state'=>0,'role'=>$this->admin->role])->find();

        if(!$priv){
            $this->error("没有权限操作");
        }

        //查看订单状态
        if($order->state != 2){
            $this->error("不能操作该订单");
        }

        $order->picture_list = json_decode($order->picture_list);
        $order_product = OrderProduct::where(['order_id'=>$order->id])->select();

        $total_number  = 0;
        $product_ids = [];
        foreach($order_product as $key => $val ){
            $total_number += intval($val['number']);
            array_push($product_ids,$val['product_id']);
        }

        $products = ProductModel::where('id','in',$product_ids)->column('title,serial_number,id','id');

        $this->data['model'] = $order;
        $this->data['order_product'] = $order_product;
        $this->data['title'] = '订单编辑';
        $this->data['user_id'] = $order->user_id;
        $this->data['expo'] = CompanyModel::where(['type'=>3])->select(); //展览中心不会很多
        $this->data['total_number'] = $total_number; //产品总的数量
        $this->data['products'] = $products;

        //页面还需要的数据
        //订单产品总数  total_number  产品的名称

        return view("", $this->data);
    }



    /**
     * 下订单的审核选择产品 的列表
     */
    public function productList(){

        $products = ProductModel::where([])->paginate(10);
        //查找工厂

        $factory_list = [];
        foreach($products as $key => $val ){
            array_push($factory_list,$val['factory_id']);
        }

        $list = [];
        if($factory_list){
            $list = CompanyModel::where('id','in',$factory_list)->column('company_name','id');
        }

        $this->data['title'] = '产品列表';
        $this->data['column'] = [
            'title'=>['name'=>'名称','fun'=>'text','options'=>''],
            'serial_number'=>['name'=>'产品编号','fun'=>'text','options'=>''],
            'market_price'=>['name'=>'市场价格','fun'=>'text','options'=>''],
            'sell_price'=>['name'=>'团购价格','fun'=>'text','options'=>''],
            'salary'=>['name'=>'佣金','fun'=>'text','options'=>''],
            'factory_id'=>['name'=>'所属工厂','fun'=>'translateMulti','options'=>['map'=>$list]],
            'add_time'=>['name'=>'添加时间','fun'=>'datetime','options'=>['format'=>'Y-m-d']],
        ];
        $this->data['model'] = $products;
        $this->data['parser'] = new Parser();
        return view('',$this->data);
    }


    /**
     * 获取商品的信息
     * @param Request $request
     * @throws \think\exception\DbException
     */
    public function getProduct(Request $request){
        $id = $request -> param('product_id');
        $product = ProductModel::get($id);

        $this->success('获取成功','',$product);
    }


    /**
     * 添加订单  关联 order order_product order_
     * @param Request $request
     * @throws
     */
    public function create(Request $request){
        $post = $request->post();
        $result = $this->handle($post);

        Db::startTrans();
        try{
            $order = OrderModel::create($result['data']);

            foreach($result['product_data'] as $key => &$val){
                $val['order_id'] = $order->id;
            }
            Db::table('order_product')->insertAll($result['product_data']);

            OrderOperate::create([
                'op_user'  => $this->admin->id,
                'order_id' => $order->id,
                'action'   => 0,
                'add_time' => time()
            ]);

            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage().':'.$e->getCode().":".$e->getLine().":".$e->getFile());
        }

        //不能在try中 使用 会跳进 catch的
        $this->success("操作成功");
    }


    /**
     * 客服可以对未审核的订单 做全部的修改
     * 跟创建订单差不多 区别就是 订单的id相同
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function update(Request $request){
        $post = $request->post();

        if(empty($post['id'])){
            $this->error("");
        }
        //检查这个订单是不是该客服的订单
        $order = OrderModel::get($post['id']);
        $exists = DistributeUser::where('admin_id',$this->admin->id)->where('user_id',$order->user_id)->count();
        if(!$exists){
            $this->error("你没有修改该订单的权限");
        }

        $result = $this->handle($post);

        Db::startTrans();
        try{
            //更新不能create了
            $orderModel = new OrderModel();
            $orderModel->save($result['data'],['id'=>$order->id]);

            foreach($result['product_data'] as $key => &$val){
                $val['order_id'] = $post['id'];
            }

            //先删除原来的产品记录
            Db::table('order_product')->where(['order_id'=>$order->id])->delete();
            //重新插入
            Db::table('order_product')->insertAll($result['product_data']);

            //state 客服修改订单 这里只有这一种
            OrderOperate::log($this->admin->id,$order->id,0,$post['message']);

            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage().':'.$e->getCode().":".$e->getLine().":".$e->getFile());
        }

        //不能在try中 使用 会跳进 catch的
        $this->success("操作成功");

    }


    /**
     * 构造订单所需要的数据
     * @param $post
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function handle($post){
        $validate = Loader::validate('Order');
        if(!$validate->check($post)){
            $this->error($validate->getError());
        }


        //判断product_list 是否有不同工厂的产品  只用到前端传来的参数 id number 其他的后台重新计算
        $product_list = [];
        $number_list = [];
        foreach($post['product_list'] as $key => $val ){
            //数量为0的产品忽略
            if(!empty($val['number'])){
                array_push($product_list,$val['id']);
                $number_list[$val['id']] = $val['number'];
            }
        }
        $product_list = ProductModel::where('id','in',$product_list)->column('id,factory_id,sell_price,salary,market_price','id');
        $factory_list = [];
        foreach($product_list as $key => $val ){
            array_push($factory_list,$val['factory_id']);
        }
        $factory_list = array_unique($factory_list);
        if(count($factory_list) != 1){
            $this->error("一个订单不能有两个工厂的商品");
        }

        //计算总价格 和 总佣金 构造产品数据
        $total_price = 0;
        $total_salary = 0;
        $product_data = [];
        foreach( $product_list as $key => $val ){
            $item_total_price = floatval($val['sell_price']) * $number_list[$val['id']];
            $item_total_salary = floatval($val['salary']) * $number_list[$val['id']];
            $total_price += $item_total_price;
            $total_salary += $item_total_salary;
            $product_data[$val['id']]['product_id'] = $val['id'];
            $product_data[$val['id']]['total_price'] = $item_total_price;
            $product_data[$val['id']]['total_salary'] = $item_total_salary;
            $product_data[$val['id']]['number'] = $number_list[$val['id']];
            $product_data[$val['id']]['sell_price'] = $val['sell_price'];
            $product_data[$val['id']]['salary'] = $val['salary'];
            $product_data[$val['id']]['market_price'] = $val['market_price'];
        }


        $data['op_user'] = $this->admin->id;
        $data['user_id'] = $post['user_id'];
        $data['order_num'] = create_order_num();
        $data['total_price'] = $total_price;
        $data['total_salary'] = $total_salary;
        $data['company_one_id'] = 0;  //用户选择
        $data['company_two_id'] = 0;   //根据地区
        $data['company_three_id'] = $factory_list[0];
        $data['company_four_id'] = $post['company_four_id'];  //用户选择
        $data['picture_list'] = json_encode($post['picture_list']);
        //$data['desc'] = $post['desc'];
        $data['state'] = 0;
        //展览id到底是传进来 还是 找最后一个  感觉传进来会好一点
        $data['exhibition_id'] = 0;
        $data['address'] = $post['address'];
        $data['zcode'] = $post['zcode'];
        $data['cellphone'] = $post['cellphone'];
        $now = time();
        $data['add_time'] = $now;
        $data['update_time'] = $now;

        $exhibition = ExhibitionModel::where('exhibition_time','>',time())->where('state',0)->order('exhibition_time desc')->find();
        $data['exhibition_id'] = $exhibition['id'];

        //找到B端， 城市运营商  B端是在用户 报名的时候已经选择好的   城市运营商根据地区获取    如果B端 用户没有选 要不要随机给他一个   不需要了 因为在报名的时候已经随机给了一个了 城市运营商也在开始的时候就给出
        $enroll = EnrollModel::where('user_id',$post['user_id'])->where('exhibition_id',$exhibition['id'])->order('id desc')->find();
        $data['company_one_id'] = $enroll['company_one_id'];
        $data['company_two_id'] = $enroll['company_two_id'];


        return [
          'data'=>$data,
          'product_data'=>$product_data
        ];
    }


    /**
     * 只有状态为0的订单才可以删除
     * 状态为-1 表示删除
     * 只有客服这里可以删除订单 其他的角色都不能删除
     * @param Request $request
     * @throws
     */
    public function delete(Request $request){
        $id = $request->param('id');
        //检查是否有权限
        $order = OrderModel::get($id);
        if(!$order){
            $this->error("订单不存在");
        }
        $exists = DistributeUser::where('admin_id',$this->admin->id)->where('user_id',$order->user_id)->count();
        if(!$exists){
            $this->error("你没有删除该订单的权限");
        }
        if($order->state){
            $this->error("该订单不能删除");
        }

        Db::startTrans();
        try{
            $order->state = -1;
            $order->save();
            OrderOperate::log($this->admin->id,$order->id,$order->state);
            Db::commit();
        }catch (\Exception $e){
            $this->error("删除失败");
        }

        $this->success("删除订单成功");
    }


    public function column(){
        return [
            'order_num'   =>['name'=>'订单编号','fun'=>'text','options'=>''],
            'total_price' =>['name'=>'总金额','fun'=>'text','options'=>''],
            'total_salary'=>['name'=>'总佣金','fun'=>'text','options'=>''],
            'cellphone'   =>['name'=>'联系人手机','fun'=>'text','options'=>''],
            'add_time'    =>['name'=>'添加时间','fun'=>'datetime','options'=>['format'=>'Y-m-d H:i']],
            'state'       =>['name'=>'订单状态','fun'=>'translate','options'=>['map'=>get_order_state()]],
            'update_time' =>['name'=>'更新时间','fun'=>'text','options'=>[]],
        ];
    }


}